// 新增角色
var request_role_new = function(data, resolve, reject) {
    mdTool.request({
        url: '/a/sys/operator',
        method: 'PUT',
        data: data,
        success: resolve,
        error: reject
    })
};
// 修改用户
var request_role_edit = function(data, resolve, reject) {
    mdTool.request({
        url: '/a/sys/operators',
        method: 'POST',
        data: data,
        success: resolve,
        error: reject
    })
};
// 删除用户
var request_role_del = function(data, resolve, reject) {
    mdTool.request({
        url: '/a/sys/operator',
        method: 'delete',
        data: data,
        success: resolve,
        error: reject
    })
};
// 获取用户
var request_role_get = function(id, resolve, reject) {
    mdTool.request({
        url: '/a/sys/operator',
        method: 'get',
        data: "id=" + encodeURIComponent(id),
        success: resolve,
        error: reject
    })
};

var roleManage = function() {

	var _init = function() {

		var table = $('#table_role');
		

		table.dataTable({
					"processing" : true,
					// 开启服务器模式
					serverSide : true,
					"ajax" : {
						url : "/a/sys/operators", // 列表查询
					// data: json
					},
					"autoWidth" : false,
					"columns" : [
						/*	{
								"width" : "5%",
								"data" : "null",
								"defaultContent" : "<label class=\"mt-checkbox mt-checkbox-single mt-checkbox-outline\"><input type=\"checkbox\" class=\"checkboxes\" value=\"1\"><span></span></label>"
							},*/
							{
								"width" : "10%",
								"data" : "name"
							},
							{
								"width" : "15%",
								"data" : "phone"
							},
							{
								"width" : "15%",
								"data" : "loginName"
							},
							{
								"width" : "15%",
								"data" : "roleId",
								"render":function(data, type, row, meta) {
									var val="--";
									if(data!=null&&data!=''){

			            				$.ajax({
			            					url : '/a/sys/torole',
			            					type : 'post',
			            					dataType : 'json',
			            					contentType:"application/json; charset=utf-8",
			            					async: false,
			            					data : JSON.stringify({ id: data }),
			            				}).done(function(r) {
			            					if (r.status === '1') { 
			            						val=r.data.name;
			            					} else if (r.status == '2') {
			            					
			            					}
			            				});
			            				return val;
			                    	}else
			                    		return "--";
									
									return val ;
								}
							},
							{
								"width" : "15%",
								"data" : "createDate"
							},
							{
								"width" : "25%",
								"data" : "null",
								"defaultContent" : "<button type=\"button\" class=\"btn blue btn_edit_role\">修改</button><button type=\"button\" class=\"btn red btn_del_role\">删除</button><button type=\"button\" class=\"btn yellow btn_repwd_role\">重置密码</button>"
							} ],
					"language" : {
						"lengthMenu" : "每页显示 _MENU_ 条记录",
						"emptyTable" : "暂无数据记录",
						"info" : "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
						"zeroRecords" : "没有搜索到匹配记录",
						"infoEmpty" : "",
						"infoFiltered" : "",
						"processing" : ""
					},
					"pageLength" : 5,
					"order" : [ [ 1, "asc" ] ],
					"columnDefs" : [ {
						"orderable" : false,
						"targets" : [ 0, 5 ]
					}, {
						"targets" : 1,
						"render" : function(data, type, row, meta) {
							return data;
						}
					}, {
						"targets" : 2,
						"render" : function(data, type, row, meta) {
							return data;
						}
					}, {
						"targets" : 3,
						"render" : function(data, type, row, meta) {
							return data;
						}
					} , {
						"targets" : 0,
						"render" : function(data, type, row, meta) {
							return data;
						}
					} , {
						"targets" : 4,
						"render" : function(data, type, row, meta) {
							return moment(data).format('YYYY-MM-DD HH:mm');
						}
					} ],
					"dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
	                "<t>" +
	                "<'row'<'col-md-5'i><'col-md-7'>p>",
					"fnInitComplete" : function() {
					}
				});

		// 选择列表
		table.find('.group-checkable').change(function() {
			var set = $(this).attr("data-set");
			var checked = $(this).is(":checked");
			$(set).each(function() {
				if (checked) {
					$(this).prop("checked", true);
					$(this).parents('tr').addClass("active");
				} else {
					$(this).prop("checked", false);
					$(this).parents('tr').removeClass("active");
				}
			});
		});
		table.on('change', 'tbody tr .checkboxes', function() {
			$(this).parents('tr').toggleClass("active");
		});

		// 表单验证
		function validate(value, type) {
			// 非空验证
			if (type === 'null') {
				return value.indexOf(' ')>0;
			}
			
			// 字段值
			var value = $.trim(value);

			// 非空验证
			if (type === 'require') {
				return !!value;
			}
			//汉字验证
			if(type === 'ecode'){
				return  /[^u4e00-u9fa5]/.test(value);
			}
			// 手机号验证
			if (type === 'phone') {
				return /^1[0-9]{10}$/.test(value);
//				return /^1[3|4|5|8][0-9]{9}$/.test(value);
			}
			// 邮箱验证
			if (type === 'email') {
				return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value);
			}
		}
		;

		// 关闭弹框
		$(".modal").on('hidden.bs.modal', function(e) {
			$('.modal .help-block').html(''); // 清空提示
			$('.modal input').val(''); // 清空 input
		});
		// 添加
		$('#btn_new_role').click(function(event) {
			$('#modal_new_role').modal('show');
		});
	
		// 确定添加
		$('#modal_sure_new').click(function() {
			var name = $('#modal_new_role [name="input_name"]').val();
			var password = $('#modal_new_role [name="input_password"]').val();
			var phone = $('#modal_new_role [name="input_phone"]').val();
			var loginName = $('#modal_new_role [name="input_loginName"]').val();
			var roleId = $('#modal_new_role [name="input_roleId"]').val();
			var param={"name":name,"password":password,"phone":phone,"loginName":loginName,"roleId":roleId};
			
			if (!validate(name, 'require')) {
				$('#modal_new_role .help-block').html('请填写店员姓名'); 
				return;
			}if (!validate(password, 'require')) {
				$('#modal_new_role .help-block').html('请填写密码');
				return;
			}if (validate(password, 'null')) {
				$('#modal_new_role .help-block').html('密码不能包含空格');
				return;
			}if (!validate(phone, 'require')) {
				$('#modal_new_role .help-block').html('请填写手机');
				return;
			}if (!validate(loginName, 'require')) {
				$('#modal_new_role .help-block').html('请填写用户编号');
				return;
			}
			if (validate(loginName, 'ecode')) {
				$('#modal_new_role .help-block').html('用户工号不能输入汉字');
				return;
			}
			if (!validate(roleId, 'require')) {
				$('#modal_new_role .help-block').html('请填写角色');
				return;
			}if (!validate(phone, 'phone')) {
				$('#modal_new_role .help-block').html('手机格式不正确，请修改');
				return;
			} else {
				$.ajax({
					url : '/a/sys/operator',
					type : 'put',
					dataType : 'json',
					contentType:"application/json; charset=utf-8",
					data : JSON.stringify(param),
				}).done(function(data) {
					if (data.status === '1') {
						// 正确
						table.DataTable().ajax.reload(); // 刷新table
						$('#modal_new_role').modal('hide');
					} else if (data.status === '2') {
//						错误
						$('#modal_new_role .help-block').html(data.message); // 返回错误信息
					}
				});
			}
		});

		// 修改
		table.on('click', '.btn_edit_role', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			var name = oData_arr[0].name;
			var phone = oData_arr[0].phone;
			var roleId = oData_arr[0].roleId;
			$('#modal_edit_role').find('input[type=hidden]').val(_id);
			$('#modal_edit_role [name="input_name"]').val(name);
			$('#modal_edit_role [name="input_phone"]').val(phone);
			$('#modal_edit_role [name="input_roleId"]').val(roleId);
			$('#modal_edit_role').modal('show');
		});
	
		
		
		// 确定修改
		$('#modal_sure_edit').click(function() {
//			var _role = $('#modal_edit_role [name="input_role"]').val();
			var _id = $('#modal_edit_role input[type=hidden]').val();
			var name = $('#modal_edit_role [name="input_name"]').val();
			var phone = $('#modal_edit_role [name="input_phone"]').val();
			var roleId = $('#modal_edit_role [name="input_roleId"]').val();
			var param={"name":name,"phone":phone,"roleId":roleId,"id":_id};
		
			if (!validate(name, 'require')) {
				$('#modal_edit_role .help-block').html('请填写店员姓名'); 
				return;
			}if (!validate(phone, 'require')) {
				$('#modal_edit_role .help-block').html('请填写电话');
				return;
			}if (!validate(roleId, 'require')) {
				$('#modal_edit_role .help-block').html('请填写角色');
				return;
			}if (!validate(phone, 'phone')) {
				$('#modal_edit_role .help-block').html('电话格式不正确，请修改'); 
				return;
			}else {
				 $.ajax({
				 url: '/a/sys/operators',
				 type: 'POST',
				 dataType: 'json',
				 contentType:"application/json; charset=utf-8",
				 data: JSON.stringify(param),
				 })
				 .done(function(data) {
					 if (data.status === '1') {
							// 正确
							table.DataTable().ajax.reload(); // 刷新table
							$('#modal_edit_role').modal('hide');
						} else if (data.status === '2') {
//							错误
							$('#modal_edit_role .help-block').html(data.msg); // 返回错误信息
						}
				 });
			}
		});

		// 删除
		table.on('click', '.btn_del_role', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要删除",
				title : "提示",
				buttons : {
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
//							alert('提交删除');
							$.ajax({
								 url: '/a/sys/operator',
								 type: 'delete',
								 dataType: 'json',
								 contentType:"application/json; charset=utf-8",
								 data: JSON.stringify({
										id : _id
									}),
								 })
								 .done(function(data) {
									 table.DataTable().ajax.reload();
								 });
						}
					},cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					}
				}
			});
		});
		
		// 重置密码
		table.on('click', '.btn_repwd_role', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr"))
					.data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要重置密码？(默认密码为123456)",
				title : "提示",
				buttons : {
					
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
//							
							$.ajax({
								 url: '/a/sys/operatorpwd',
								 type: 'put',
								 dataType: 'json',
								 contentType:"application/json; charset=utf-8",
								 data: JSON.stringify({
										id : _id
									}),
								 })
								 .done(function(data) {
									 table.DataTable().ajax.reload();
								 });
						}
					},cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					}
				}
			});
		});
	}

	return {
		init : function() {
			_init();
		}

	};

}();

$(function() {
	roleManage.init();
	
});
